/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.skatiger.jrove;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.skatiger.jrove.tag.CompositeHandler;
import org.skatiger.jrove.tag.Tag;
import org.skatiger.jrove.tag.TagAttribute;
import org.skatiger.jrove.tag.TagException;

public abstract class TagHandler
        implements JroveHandler {

    protected final String tagId;

    protected final Tag tag;

    protected final JroveHandler nextHandler;

    public TagHandler(TagConfig config) {
        this.tagId = config.getTagId();
        this.tag = config.getTag();
        this.nextHandler = config.getNextHandler();
    }

    @SuppressWarnings("unchecked")
    protected final <T> Iterator<T> findNextByType(Class<T> type) {
        List<T> found = new ArrayList<T>();
        if (type.isAssignableFrom(this.nextHandler.getClass())) {
            found.add((T) this.nextHandler);
        } else if (this.nextHandler instanceof CompositeHandler) {
            JroveHandler[] h = ((CompositeHandler) this.nextHandler).getHandlers();
            for (JroveHandler handler : h) {
                if (type.isAssignableFrom(handler.getClass())) {
                    found.add((T) handler);
                }
            }
        }
        return found.iterator();
    }

    /**
     * Utility method for fetching the appropriate TagAttribute
     * 
     * @param localName
     *            name of attribute
     * @return TagAttribute if found, otherwise null
     */
    protected final TagAttribute getAttribute(String localName) {
        return this.tag.getAttributes().get(localName);
    }

    /**
     * Utility method for fetching a required TagAttribute
     * 
     * @param localName
     *            name of the attribute
     * @return TagAttribute if found, otherwise error
     * @throws TagException
     *             if the attribute was not found
     */
    protected final TagAttribute getRequiredAttribute(String localName) throws TagException {
        TagAttribute attr = this.getAttribute(localName);
        if (attr == null) {
            throw new TagException(this.tag, "Attribute '" + localName + "' is required");
        }
        return attr;
    }

    @Override
    public String toString() {
        return this.tag.toString();
    }
}
